<template>
  <div>
    <!-- 请勿修改，（选择全部员工）  -->
    <a-modal :width="720" title="新增管理员" :visible="show" @cancel="cancel">
      <template slot="footer">
        <div>
          <a-button @click="cancel"> 取消 </a-button>
          <a-button key="submit" type="primary" @click="ok"> 确定 </a-button>
        </div>
      </template>
      <a-spin :spinning="spinning">
        <div class="employee-selector-wrapper2">
          <div>
            <div class="employee-selector-block">
              <a-input-search placeholder="请输入搜索内容" style="width: 100%" @search="searchPeople" @change="changePeople" />
            </div>
            <!-- <a-tabs default-active-key="1" @change="onChangeTab" style="margin-bottom:10px;width:450px" size="small" :tabBarGutter="3">
              <a-tab-pane key="1" tab="全部待添"> -->
            <div class="tree-item2">
              <div>全选当页</div>
              <a-checkbox :checked="isAllSelected" @click="choseAll(treeData)" class="iconStyle"> </a-checkbox>
              <!-- <img v-else @click="choseAll(treeData)" src="@/assets/icons/未选择.png" style="width:18px;height:18px;margin-left:10px" /> -->
            </div>
            <div class="employee-selector">
              <div v-for="(item, index) in treeData" :key="index" class="mg_t10">
                <div class="tree-item" @click="chose(item, treeData)">
                  <span>
                    <img src="@/assets/icons/person1.png" style="width: 30px; height: 30px; margin-right: 10px" />
                    {{ item.name }}
                    {{ item.phone ? "(" + item.phone + ")" : "" }}
                  </span>
                  <a-checkbox v-on:click.stop="chose(item, treeData)" :checked="item.isSelected" class="iconStyle"> </a-checkbox>
                  <!-- <img v-else v-on:click.stop="chose(item, treeData)" src="@/assets/icons/未选择.png" style="width:18px;height:18px;" /> -->
                </div>
              </div>
            </div>
            <a-pagination
              v-model="current"
              size="small"
              :page-size-options="pageSizeOptions"
              :total="total"
              show-size-changer
              show-less-items
              :page-size="pageSize"
              @showSizeChange="onShowSizeChange"
              @change="onPageChange"
            >
              <template slot="buildOptionText" slot-scope="props">
                <span>{{ props.value }}条/页</span>
              </template>
            </a-pagination>
            <!-- </a-tab-pane>
            </a-tabs> -->
          </div>
          <!-- <div class="verticalBar" /> -->

          <div class="employee-selector-block2">
            <div class="employee-selector-title" style="display: flex; justify-content: space-between">
              <div>
                当前选中 <span class="empNumber">{{ selectedListTemp.length }}</span
                >人
              </div>
              <div @click="deleteAllItem" class="empNumber" style="font-size: 14px; cursor: pointer; margin-right: 10px">清空</div>
            </div>
            <div class="employee-selector">
              <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
                <div>
                  <img src="@/assets/icons/person1.png" style="width: 30px; height: 30px; margin-right: 10px" />
                  {{ item.name }}
                </div>
                <img @click="deleteItem(item, i)" src="@/assets/icons/删除.png" style="width: 20px; height: 20px" />
              </div>
            </div>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getAllEmp } from "@/api/outsourcing/outsourcing";
import { getSalaryCalculateRuleGroups } from "@/api/outsourcing/outrules";

import moment from "moment";
export default {
  props: {
    status: {
      type: Number,
      default: 2,
      require: true
    },
    yearly: {
      type: String,
      default: "",
      require: true
    },
    monthly: {
      type: String,
      default: "",
      require: true
    },
    show: {
      type: Boolean,
      default: false
    },
    number: {
      type: Number,
      default: 0
    },
    templateId: {
      type: Number,
      default: 0
    },
    defaultSelectedKeys: {
      type: Array,
      default: () => []
    },
    selectedList: {
      type: Array,
      default: () => []
    },
    isOnlineOrLeave: {
      type: Boolean,
      default: true
    },
    groupId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      dataList: [],
      nameOrPhone: "",
      spinning: false,
      selectedRowKeys: [],
      copyVisible: false,
      importDataLength: 0,
      labelCol: { span: 7 },
      wrapperCol: { span: 16 },
      mode: "1",
      form: {},
      labelList: [],
      treeData: [],
      errorState: false,
      selectedListTemp: [],
      chosenList: [],
      serviceFeeRuleList: [],
      rulusList: [],
      isAllSelected: false,
      seniorVisible: false,
      checkStatue: 0,
      textContent: "",
      selectedKeysBeforeSearch: [],

      postTypeValue: 3,
      pageSizeOptions: ["10", "20", "50", "100"],
      pageSize: 10,
      current: 1,
      total: 50,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "small",
        current: 1,
        showTotal: (total) => `共 ${total} 条`
      }
    };
  },
  watch: {
    textContent(e) {
      if (e) {
        this.errorState = false;
      }
    },

    show(val) {
      if (val) {
        this.selectedListTemp = JSON.parse(JSON.stringify(this.selectedList));
        this.treeData = [];
        this.current = 1;
        this.postTypeValue = 3;
        this.mode = "1";
        this.importDataLength = this.selectedList.length;
        // this.onPageChange(1);
        this.spinning = false;
        this.getSelectDepTree();
      }
    },

    month(val) {}
  },
  created() {},
  methods: {
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      // this.checkStatue = 0;
      this.getSeniorList();
    },
    // 分页变化
    update() {
      this.rulusList = [];
      getSalaryCalculateRuleGroups({
        companyId: this.$store.state.hr.companyId
      }).then((res) => {
        if (res.data.length > 0) {
          res.data.map((item) => {
            if (item.ruleType === 1) {
              this.rulusList.push(item);
            }
            if (item.ruleType === 2) {
              this.serviceFeeRuleList.push(item);
            }
          });
        }
      });
    },
    onPageChange(pageNumber) {
      this.current = pageNumber;
      this.getSelectDepTree();
    },

    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
      this.current = 1;
      this.getSelectDepTree();
    },
    choseAll(data) {
      this.isAllSelected = !this.isAllSelected;
      var that = this;
      this.spinning = true;
      for (var j = 0, len = data.length; j < len; j++) {
        data[j].isSelected = that.isAllSelected;
        that.ergodicAll(data[j]);
      }
      setTimeout(function () {
        that.spinning = false;
      }, "10");
    },
    chose(item, data) {
      item.isSelected = !item.isSelected;
      this.onChange(item);
    },
    onChangeTab(e) {
      this.isAllSelected = false;
      this.current = 1;
      this.mode = e;
      this.getSelectDepTree();
    },
    onChange(item) {
      this.spinning = true;
      var that = this;
      setTimeout(function () {
        that.$nextTick(() => {
          that.ergodic(item);
        });

        that.spinning = false;
      }, "10");
    },

    ergodic(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex((it) => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
          this.isAllSelected = false;
          this.treeData.some((e) => {
            if (e.id === item.id) {
              e.isSelected = false;
              return true;
            }
          });
        }
      } else {
        if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);

          var count = this.treeData.length;
          var allSelect = true;
          for (var i = 0; i < count; i++) {
            if (!this.treeData[i].isSelected) {
              allSelect = false;
              break;
            }
          }
          this.isAllSelected = allSelect;
        }
      }
    },
    ergodicAll(item) {
      if (!item.isSelected) {
        var index = this.selectedListTemp.findIndex((it) => it.id === item.id); // 存在再删除，防止删除错误
        if (index !== -1) {
          this.selectedListTemp.splice(index, 1); // 删除
        }
      } else {
        if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
          // 不存在再添加，防止重复添加
          this.selectedListTemp.push(item);
        }
      }
    },

    // 获取部门树
    getSelectDepTree(query) {
      if (query) {
        this.current = 1;
      }
      const params = {
        // onlyCurrentDep: true,
        // onlyUser: true,
        pageSize: this.pageSize,
        pageNo: this.current,
        groupId: this.groupId
      };

      if (this.nameOrPhone) {
        params["nameOrPhone"] = this.nameOrPhone;
      }

      this.spinning = true;

      getAllEmp(params)
        .then((res) => {
          this.spinning = false;
          if (res.data.entities === null) {
            this.$message.success("暂无数据");
            this.treeData = [];
            this.total = 0;
            this.isAllSelected = false;
          } else {
            this.treeData = this.formatCompanyData(res.data.entities);
            this.total = res.data.entityCount;
            var count = res.data.entities.length;
            this.pageSize = res.data.pageSize;
            this.current = res.data.pageNo;
            var allSelect = true;
            this.spinning = false;

            if (count !== 0) {
              for (var i = 0; i < count; i++) {
                if (!this.treeData[i].isSelected) {
                  allSelect = false;
                  break;
                }
              }

              this.isAllSelected = allSelect;
            } else {
              this.isAllSelected = false;
            }
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
          this.spinning = false;
        });
    },
    formatCompanyData(company) {
      const parent = [];
      for (var key = 0; key < company.length; key++) {
        var selected = false;

        this.selectedListTemp.forEach((item, index) => {
          if (item.id === company[key].id) {
            selected = true;
          }
        });
        var emp = {
          id: company[key].id,
          name: company[key].name,
          phone: company[key].phone,
          idCard: company[key].idCard,
          depName: company[key].depName,
          positionName: company[key].positionName,
          isSelected: selected
        };
        // this.selectedListTemp = this.selectedList;
        this.selectedListTemp.forEach((item, index) => {
          item.isSelected = true;
        });

        parent.push(emp);
      }
      this.importDataLength = 0; // 清空传入的默认值
      return parent;
    },
    searchPeople(query) {
      this.pageSize = 10;
      this.current = 1;
      this.nameOrPhone = query;

      this.selectedKeysBeforeSearch = this.selectedListTemp.map((item) => item.id);
      this.getSelectDepTree(query);
    },
    changePeople(e) {
      if (e.target.value === "") {
        this.pageSize = 10;
        this.current = 1;
        this.getSelectDepTree();
        this.selectedKeysBeforeSearch = this.selectedListTemp.map((item) => item.id);
      }
    },
    deleteAllItem() {
      this.spinning = true;
      this.selectedListTemp.forEach((item) => {
        item.isSelected = false;
        var that = this;
        setTimeout(function () {
          that.$nextTick(() => {
            that.ergodic(item);
          });
        });
      });
      this.spinning = false;
    },
    deleteItem(item, index) {
      this.spinning = true;
      item.isSelected = false;
      var that = this;
      setTimeout(function () {
        that.$nextTick(() => {
          that.ergodic(item);
        });

        that.spinning = false;
      }, 1000);
    },

    ok() {
      if (this.selectedListTemp.length === 0) {
        this.$message.success("请选择人员");
        return;
      }
      console.log(this.selectedListTemp);
      // if (this.selectedListTemp.length > 50) {
      //   this.$message.success("一次性最多选择50人");
      //   return;
      // }
      this.$emit("update:selectedList", this.selectedListTemp);
      this.$emit(
        "update:selectThree",
        this.selectedListTemp
          .slice(0, 3)
          .map((item) => item.name)
          .join(",")
      );
      this.$emit("update:show", false);
      this.$emit("change", this.selectedListTemp);
    },
    cancel() {
      this.$emit("update:show", false);
    }
  }
};
</script>
<style lang="scss" scoped>
.postTypeL {
  display: flex;

  flex-direction: row;
  align-items: center;
}
.employee-selector {
  height: 410px;
  margin-top: 2px;
  padding-right: 10px;
  margin-bottom: 10px;
  overflow: auto;
}
.verticalBar {
  width: 1px;
  background: #e8e8e8;
  display: inline-block;
  margin-top: 40px;
  vertical-align: top;
  margin-right: 30px;
  margin-left: 30px;
  html,
  body,
  #app {
    height: 100%;
  }
}
.tree-item {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 10px;
}
.tree-item2 {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  margin-top: 24px;
  margin-bottom: 10px;
}
.employee-selector-wrapper2 {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  .employee-selector-block {
    width: 390px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 400px;
      margin-top: 20px;
      padding-right: 20px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
  .employee-selector-block2 {
    width: 400px;
    background: #f4f6fa;
    border-radius: 8px;
    padding: 6px 6px 16px 16px;
    margin-left: 16px;
    .employee-selector-title {
      width: 100%;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
    .employee-selector {
      height: 452px;
      margin-top: 8px;
      padding-right: 10px;
      overflow: auto;
      .employee-selector-item {
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
      }
    }
  }
}
.empNumber {
  color: var(--primary);
}
.iconStyle {
  margin-left: 10px;
  font-size: 18px;
  color: var(--primary);
}
.count {
  color: var(--primary);
  font-size: 16px;
}
</style>
